package com.eample.pages;

import static org.openqa.selenium.support.ui.ExpectedConditions.alertIsPresent;

import java.util.List;

import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.ui.Select;

import com.example.tests.SortedListOf;
import com.example.tests.User;
import com.google.common.collect.Lists;

public class UserPage extends InternalPage {

	@FindBy(id = "username")
	public WebElement userName;

	@FindBy(name = "email")
	public WebElement emalField;

	@FindBy(id = "password")
	public WebElement insPassword1;

	@FindBy(id = "password2")
	public WebElement insPassword2;

	@FindBy(name = "permission")
	public WebElement selectPermission;

	@FindBy(name = "submit")
	public WebElement saveButoon;

	@FindBy(xpath = ("//div[@id='content']/section/div[2]/table/tbody/tr[2]/td[6]/a/img"))
	public WebElement delUserEditor;
	
	@FindBy(css="div#user-list table >tbody >tr")
	public List<WebElement>userRows;

	public UserPage InsUser(User user) {

		userName.sendKeys(user.name);

		emalField.sendKeys(user.email);

		insPassword1.sendKeys(user.password);

		insPassword2.sendKeys(user.password);

		new Select(driver.findElement(By.name("permission")))
				.selectByVisibleText("Editor");
		saveButoon.click();
		
		return MyPageFactory.getPage(driver, com.eample.pages.UserPage.class);
	}

	
	public UserPage deleteUser(User user) {
		
		for (WebElement row:userRows){
			
			if (user.equals(convertRowToUser(row))){
				row.findElement(By.xpath("./td[6]/a")).click();
				wait_().until(alertIsPresent()).accept();
				break;
			}
		}
			
		
		return MyPageFactory.getPage(driver, UserPage.class);
	}
	
	public UserPage delUser() {
		delUserEditor.click();
		wait_().until(alertIsPresent()).accept();
		return MyPageFactory.getPage(driver, com.eample.pages.UserPage.class);
	}

	public SortedListOf<User> getUsers() {
		List<User> users = Lists.newArrayList();
		for (WebElement row:userRows){
			users.add(convertRowToUser(row));
		}
		
		return new SortedListOf<User>(users);
	}

	private User convertRowToUser(WebElement row) {
		List<WebElement> cells = row.findElements(By.tagName("td"));
		return new User()
			.withName(cells.get(1).getText())
			.withEmail(cells.get(2).getText())
			.withRole(cells.get(3).getText());
			
		
	}

	

	

	
	
}
